import React, { useEffect, useState, Component, useRef } from 'react';
import { fetchSync, request } from '@/utils/request';
import { history, Link } from 'umi';
import { connect, router } from 'dva';

import enUS from 'antd/es/locale/en_US';
import {
    Menu, Switch, Divider, Checkbox, Button, Row, Col, Tooltip, notification, Skeleton, Avatar, Popconfirm,
    Form, Modal, Select, Tree, Icon, Radio, Table, Tag, Pagination, Input, Space, message, Card, Tabs, Collapse, Image, ConfigProvider
} from 'antd';
import { MailOutlined, AppstoreOutlined, SettingOutlined, AudioOutlined, UserOutlined, ArrowRightOutlined, ArrowLeftOutlined } from '@ant-design/icons';

import 'mapbox-gl/dist/mapbox-gl.css';
import styles from './vip.less';
import { getByParam, getUserId } from '@/utils/loginAssert';
import moment from 'moment';
import { getDaysDifference } from '@/utils/common';

let benefits = [
    {
        name: 'Activities',
        icon: require('./img/logo.png'),
    },
    // {
    //     name: 'Discount',
    //     icon: require('./img/logo.png'),
    // },
    {
        name: 'Exclusive logo',
        icon: require('./img/logo.png'),
    },
    // {
    //     name: 'Coupon',
    //     icon: require('./img/logo.png'),
    // }
];

let costs = [{
    name: 'Weekly',
    cost: 25,
    unit: 'week',
}, {
    name: 'Monthly',
    cost: 75,
    unit: 'month',
}, {
    name: 'Year',
    cost: 248,
    unit: 'year'
}]
export default (props) => {
    const [selectCost, setSelectCost] = useState(null);
    const [feature, setFeature] = useState({});
    const showmapContainer = useRef(null);
    const echarts8 = useRef(null);
    const commentList = useRef(null);

    const [agree, setAgree] = useState(false)

    const [selectQiangxianItem, setSelectQiangxianItem] = useState({ people: 0 })

    //初始函数
    useEffect(async () => {
        //此处编写 组件挂载之后和组件重新渲染之后执行的代码
        // qu_data = await fetchSync('/api/fangxun/qu/findAll')

        return () => {
            //此处编写 组件即将被卸载前执行的代码
        }
        // 4、若传值，但是传的是空数组 []，则表示该useEffect里的内容仅会在“挂载完成后和组件即将被卸载前”执行一次；
    }, [])

    const getCardType = () => {
        let cardTypes = getByParam('cardType')
        if (!cardTypes || cardTypes.length==0) {
            return 'No Card'
        } else if (cardTypes.includes('Year')) {
            return 'Year Card'
        } else if (cardTypes.includes('Monthly')) {
            return 'Monthly Card'
        } else if (cardTypes.includes('Weekly')) {
            return 'Weekly Card'
        }
    }

    const payFun = () => {
        if (!agree) {
            message.warning('please agree the membership agreement !')
            return;
        }
        console.log(selectCost);
        let vipDueDate = getByParam('vipDueDate')
        let cost = getByParam('cost')
        cost += selectCost.cost;
        if (moment(vipDueDate) < new Date()) {
            vipDueDate = moment().add(1, selectCost.unit).format('YYYY-MM-DD')
        } else {
            vipDueDate = moment(vipDueDate).add(1, selectCost.unit).format('YYYY-MM-DD')
        }

        let cardType = getByParam('cardType') || []
        if (!cardType.includes(selectCost.name)) {
            cardType.push(selectCost.name)
        }

        let user = JSON.parse(sessionStorage.getItem('user'))
        let data = {
            id: getUserId(),
            cardType,
            vipDueDate,
            cost
        }
        request('/api/user/update', {
            method: 'POST',
            data
        }).then(res => {
            console.log(res);
            if (res.success) {
                sessionStorage.setItem("user", JSON.stringify({ ...user, ...data }));
                message.success('success！', function () {
                    window.location.reload()
                })
            }
        })
    }

    const confirm = () => {

        let user = JSON.parse(sessionStorage.getItem('user'))
        let data = {
            id: getUserId(),
            cardType: [],
            vipDueDate: moment().format('YYYY-MM-DD'),
            cost: getByParam('cost')
        }

        request('/api/user/update', {
            method: 'POST',
            data
        }).then(res => {
            console.log(res);
            if (res.success) {
                sessionStorage.setItem("user", JSON.stringify({ ...user, ...data }));
                message.success('success！', function () {
                    window.location.reload()
                })
            }
        })
    }

    return (
        <div className={styles.container}>

            <div className={styles.header}>
                <Link to="/runjoy">
                    <Button type="link" style={{ marginTop: 12 }} shape="circle" icon={<ArrowLeftOutlined style={{ color: '#fff', fontSize: 36 }} />} />
                </Link>
                <span className={styles.title}>
                    VIP Center
                </span>
            </div>
            <br />
            <Card bordered={false}>
                <div className={styles.cardPanel}>
                    <div className={styles.desc}>
                        <label>{getCardType()}</label>
                        <span>{moment(getByParam('vipDueDate')).format('YYYY-MM-DD')}</span>
                    </div>
                    <div className={styles.remain}>
                        <b>{getDaysDifference(new Date(getByParam('vipDueDate')), new Date()) < 0 ? 0 : getDaysDifference(new Date(getByParam('vipDueDate')), new Date())}</b> day remaining
                        {
                            (moment(getByParam('vipDueDate')) - new Date() > 0) && <div>
                                <Popconfirm
                                    title="Cancel Membership"
                                    description="Are you sure to cancel this membership?"
                                    onConfirm={confirm}
                                    onCancel={() => message.error('Click on No')}
                                    okText="Yes"
                                    cancelText="No"
                                >
                                    <Button type="dashed" danger >Cancel </Button>
                                </Popconfirm>
                            </div>
                        }
                    </div>
                </div>
            </Card>
            <br />

            <Card title='Membership benefits' bordered={false} headStyle={{ color: '#c2b04d !important' }}>
                <div className={`${styles.benefitsPanel}`}>
                    {
                        benefits.map((item, idx) => {
                            return <div className={`${styles.item}`} key={idx} >
                                <img src={item.icon} width={100}></img>
                                <span>{item.name}</span>
                            </div>
                        })
                    }
                </div>
            </Card>
            <br />

            <Card bordered={false}>
                <div className={styles.costPanel}>
                    {
                        costs.map((item, idx) => {
                            return <div className={`${styles.item} ${selectCost?.name === item.name ? styles.active : ''}`} key={idx} onClick={() => setSelectCost(item)}>
                                <label>{item.name}</label>
                                <span>{`$` + item.cost + '.00'}</span>
                            </div>
                        })
                    }
                </div>
                <br />
                <Radio style={{ color: '#ddd' }} onChange={() => setAgree(true)}>Check to agree the membership agreement</Radio>
                <Button className={styles.pay} style={{ background: '#c2b04d', marginTop: 5, fontSize: 20, height: 42, lineHeight: '30px' }} block onClick={payFun}>Pay</Button>
            </Card>
        </div>
    );
}
